// 文章控制器
// const mysql = require (`mysql`);
/*eslint no-unused-vars: "warn"*/
/*eslint no-undef: "warn"*/
const fs = require(`fs`)
const path = require(`path`)
const ArticleController = {}
//导入模型
const dbQuery = require(`../model/query.js`)
const dbQueryPromise = require(`../model/query-promise.js`)
const { getUnixTime } = require(`../util/tool.js`);
// const { connect } = require('../router/router.js');
// 映射数据关系，可以用对象形式来简化if elseif
let statusTextMap = {
    0: `<span class="green">已发布</span>`,
    1: `<span class="red">未发布</span>`,
    2: `<span class="gray">审核中</span>`
}
// 统计分类文章的总数
ArticleController.cateArticleCount = async (req, res) => {
    let sql = `SELECT
    t2.cate_name,count(t1.id) as count FROM
    article t1 LEFT JOIN category t2 ON t1.cat_id = t2.cate_id
    GROUP BY t1.cat_id ;
    `;
    let result = await dbQueryPromise(sql)
    res.json(result)
}

// 文章列表
// ArticleController.index = (req, res) => {
//     let userInfo = JSON.parse(req.session.userInfo || '{}');
//     // 1. 编写sql语句
//     let sql = `select t1.*,t2.cate_name from article  as t1 
//                 left join category t2 on t1.cat_id = t2.cate_id 
//                 where t1.is_delete = 0 order by t1.id desc`;
//     // 2. 执行sql
//     dbQuery(sql, (err, rows) => {
//         let data = rows.map((item) => {
//             item.status_text = statusTextMap[item.status]
//             return item;
//         })
//         // 3. 把查询出来的数据分配到模板引擎中
//         res.render('article-list.html', { articles: data, userInfo }) 
//     })

// }

// 文章列表
ArticleController.index = (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || `{}`);
    // 1. 编写sql语句
    let sql = `select t1.*,t2.cate_name from article  as t1 
                left join category t2 on t1.cat_id = t2.cate_id 
                where t1.is_delete = 0 order by t1.id desc`;
    // 2. 执行sql
    dbQueryPromise(sql).then(rows => {
        let data = rows.map((item) => {
            item.status_text = statusTextMap[item.status]
            return item;
        })
        // 3. 把查询出来的数据分配到模板引擎中
        res.render(`article-list.html`, { articles: data, userInfo })
    })
}


// 回收站列表
// ArticleController.recyclelist = (req, res) => {
//     //编写sql
//     let sql = `select t1.*,t2.cate_name from article  as t1 
//                 left join category t2 on t1.cat_id = t2.cate_id 
//                 where t1.is_delete = 1 order by t1.id desc`;
//     //执行sql
//     dbQuery(sql, (err, rows) => {
//         console.log(rows);
//         let data = rows.map((item) => {
//             item.status_text = statusTextMap[item.status]
//             return item;
//         })
//         //把查询出来的数据分配到模板引擎中
//         res.render('recycle.html', { articles: data })
//     })

// }
// 回收站列表
ArticleController.recyclelist = (req, res) => {
    //编写sql
    let sql = `select t1.*,t2.cate_name from article  as t1 
                left join category t2 on t1.cat_id = t2.cate_id 
                where t1.is_delete = 1 order by t1.id desc`;
    //执行sql
    dbQueryPromise(sql).then(rows => {
        let data = rows.map((item) => {
            item.status_text = statusTextMap[item.status]
            return item;
        })
        //把查询出来的数据分配到模板引擎中
        res.render(`recycle.html`, { articles: data })
    })
}


// 永久删除
// ArticleController.delete = (req, res) => {
//     //接受删除文章的id
//     let { id, img } = req.query;
//     //编写sql，删除
//     let sql = `delete from article where id = ${id}`;
//     dbQuery(sql, (err, result) => {
//         if (result.affectedRows) {
//             if (img) {
//                 let oldpath = path.join(__dirname, '../', img)
//                 fs.unlink(oldpath, (err) => {
//                 })
//             }
//             res.redirect('/')
//         } else {
//             // 删除失败，响应js代码，让浏览器执行
//             res.send("<script>alert('删除失败'); location.href = '/'; </script>")
//         }
//     })
// }

// 永久删除
ArticleController.delete = (req, res) => {
    //接受删除文章的id
    let { id, img } = req.query;
    //编写sql，删除
    let sql = `delete from article where id = ${id}`;
    dbQueryPromise(sql).then(result => {
        if (result.affectedRows) {
            if (img) {
                let oldpath = path.join(__dirname, `../`, img)
                fs.unlink(oldpath, () => {
                })
            }
            res.redirect(`/`)
        } else {
            // 删除失败，响应js代码，让浏览器执行
            res.send(`<script>alert('删除失败'); location.href = '/'; </script>`)
        }
    })
}

// ajax永久删除
// ArticleController.ajaxdelete = (req, res) => {
//     // 删除文章id
//     let { id, img } = req.body;
//     // sql语句，delete
//     let sql = `delete from article where id = ${id}`;
//     dbQuery(sql, (err, result) => {
//         if (result.affectedRows) {
//             // 成功，重定向首页并删除文章的引用图片
//             if (img) {
//                 let oldpath = path.join(__dirname, '../', img)
//                 fs.unlink(oldpath, (err) => {
//                 })
//             }
//             // res.redirect('/')
//             res.json({
//                 code: 20000,
//                 message: "成功"
//             })
//         } else {
//             // 删除失败，响应js代码，让浏览器执行
//             // res.send("<script>alert('删除失败'); location.href = '/'; </script>")
//             res.json({
//                 code: -1,
//                 message: "删除失败"
//             })
//         }

//     })
// }

// ajax永久删除
ArticleController.ajaxdelete = (req, res) => {
    // 删除文章id
    let { id, img } = req.body;
    // sql语句，delete
    let sql = `delete from article where id = ${id}`;
    dbQueryPromise(sql).then(result => {
        if (result.affectedRows) {
            // 成功，重定向首页并删除文章的引用图片
            if (img) {
                let oldpath = path.join(__dirname, `../`, img)
                fs.unlink(oldpath, () => {
                })
            }
            // res.redirect('/')
            res.json({
                code: 20000,
                message: `成功`
            })
        } else {
            // 删除失败，响应js代码，让浏览器执行
            // res.send("<script>alert('删除失败'); location.href = '/'; </script>")
            res.json({
                code: -1,
                message: `删除失败`
            })
        }
    })
}

// 添加文章的表单页面
// ArticleController.add = (req, res) => {
//     // // 判断是否有session权限
//     // if(!req.session.userInfo){
//     //     res.redirect('/login');
//     //     return;
//     // }
//     // 取出分类数据分配到模板
//     let userInfo = JSON.parse(req.session.userInfo || '{}');
//     let sql = "select * from category";
//     dbQuery(sql, (err, rows) => {
//         res.render('add.html', { cats: rows, userInfo })
//     })
// }

// 添加文章的表单页面
ArticleController.add = (req, res) => {
    // // 判断是否有session权限
    // if(!req.session.userInfo){
    //     res.redirect('/login');
    //     return;
    // }
    // 取出分类数据分配到模板
    let userInfo = JSON.parse(req.session.userInfo || `{}`);
    let sql = `select * from category`;
    dbQueryPromise(sql).then(rows => {
        res.render(`addArticle.html`, { cats: rows, userInfo })
    })
}

//编辑回显
// ArticleController.edit = (req, res) => {
//     let { id } = req.query;
//     let sql1 = `select * from article where id =${id}`;
//     dbQuery(sql1, (err, rows1) => {
//         let sql2 = "select * from category";
//         dbQuery(sql2, (err, row2) => {
//             res.render('edit.html', {
//                 article: rows1[0],
//                 cats: row2
//             })
//         })
//     })
// }

// 编辑回显
ArticleController.edit = (req, res) => {
    let { id } = req.query;
    let sql1 = `select * from article where id =${id}`;
    dbQueryPromise(sql1).then(rows1 => {
        let sql2 = `select * from category`;
        dbQuery(sql2, (err, row2) => {
            res.render(`edit.html`, {
                article: rows1[0],
                cats: row2
            })
        })
    })
}

//加入回收站
// ArticleController.recycle = (req, res) => {
//     let { id = 0 } = req.query;
//     $sql = `update article set is_delete = 1 where id = ${id}`;
//     dbQuery($sql, (err, result) => {
//         let { affectedRows } = result;
//         if (affectedRows) {
//             res.redirect('/')
//         } else {
//             res.send("<srcipt>alert('失败');location.href='/';</srcipt>")
//         }
//     })
// }

// 加入回收站
ArticleController.recycle =(req, res) => {
    let { id = 0 } = req.query;
    let $sql = `update article set is_delete = 1 where id = ${id}`;
    dbQueryPromise($sql).then(result => {
        let { affectedRows } = result;
        if (affectedRows) {
            res.redirect(`/`)
        } else {
            res.send(`<srcipt>alert('失败');location.href='/';</srcipt>`)
        }
    })
}

//实现文章还原
// ArticleController.huanyuan = (req, res) => {
//     let { id = 0 } = req.query;
//     $sql = `update article set is_delete = 0 where id = ${id}`;
//     dbQuery($sql, (err, result) => {
//         let { affectedRows } = result;
//         if (affectedRows) {
//             res.redirect('/')
//         } else {
//             res.send("<script>alert('还原失败');location.href='/';</script>")
//         }
//     })
// }

// 实现文章还原
ArticleController.huanyuan = (req, res) => {
    let { id = 0 } = req.query;
    let $sql = `update article set is_delete = 0 where id = ${id}`;
    dbQueryPromise($sql).then(result => {
        let { affectedRows } = result;
        if (affectedRows) {
            res.redirect(`/`)
        } else {
            res.send(`<script>alert('还原失败');location.href='/';</script>`)
        }
    })
}

// 实现数据入库
// ArticleController.insert = (req, res) => {
//     // console.log('req.body:',req.body)
//     // console.log('req.file:',req.file)
//     // 判断是否有图片
//     let imgPath = '';
//     if (req.file) {
//         let { originalname, filename } = req.file
//         let ext = originalname.substring(originalname.indexOf('.'));
//         // 把上传成功后的文件进行重命名
//         let oldPath = path.join(__dirname, '../', 'uploads', filename);
//         let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;
//         // 数据库记录存放的路径 
//         imgPath = `uploads/${filename}${ext}`
//         fs.renameSync(oldPath, newPath)
//     }
//     // 1.接受post参数
//     let { title, author, cat_id, content, status } = req.body
//     let nowTime = getUnixTime();
//     // 2.编写sql语句插入到文章表中
//     let sql = `insert into article(title,img,author,cat_id,content,status,add_time)
//      values('${title}','${imgPath}','${author}','${cat_id}','${content}','${status}','${nowTime}')`;
//     dbQuery(sql, (err, result) => {
//         // 3.判断结果
//         if (result.affectedRows) {
//             res.send("<script>alert('成功');location.href='/';</script>")
//         } else {
//             res.send("<script>alert('失败');location.href='/add';</script>")
//         }
//         // res.send('入库中....')
//     })
// }

// 实现数据入库
ArticleController.insert = (req, res) => {
    // 判断是否有图片
    let imgPath = ``;
    if (req.file) {
        let { originalname, filename } = req.file
        let ext = originalname.substring(originalname.indexOf(`.`));
        // 把上传成功后的文件进行重命名
        let oldPath = path.join(__dirname, `../`, `uploads`, filename);
        let newPath = path.join(__dirname, `../`, `uploads`, filename) + ext;
        // 数据库记录存放的路径 
        imgPath = `uploads/${filename}${ext}`
        fs.renameSync(oldPath, newPath)
    }
    // 1.接受post参数
    let { title, author, cat_id, content, status } = req.body
    let nowTime = getUnixTime();
    // 2.编写sql语句插入到文章表中
    let sql = `insert into article(title,img,author,cat_id,content,status,add_time)
     values('${title}','${imgPath}','${author}','${cat_id}','${content}','${status}','${nowTime}')`;
    dbQueryPromise(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            res.send(`<script>alert('成功');location.href='/';</script>`)
        } else {
            res.send(`<script>alert('失败');location.href='/add';</script>`)
        }
        // res.send('入库中....')        
    })
}
// 实现编辑入库
// ArticleController.update = (req, res) => {
//     let { id, title, author, status, cat_id, content, oldImg } = req.body
//     let update_time = getUnixTime();
//     let imgPath;
//     // let bind = [title,author,status,cat_id,content,update_time,id]
//     if (req.file) {
//         let { originalname, filename } = req.file
//         let ext = originalname.substring(originalname.indexOf('.'));
//         let oldPath = path.join(__dirname, '../', 'uploads', filename);
//         let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;
//         imgPath = `uploads/${filename}${ext}`
//         fs.renameSync(oldPath, newPath)
//     } else {
//         imgPath = oldImg
//     }
//     let sql = `update article 
//     set title = '${title}',img = '${imgPath}',author= '${author}',
//     status= '${status}',cat_id= '${cat_id}',
//     content = '${content}',update_time = '${update_time}' 
//     where id = '${id}'`
//     dbQuery(sql, (err, result) => {
//         if (result.affectedRows) {
//             if (req.file) {
//                 let oldpath = path.join(__dirname, '../', oldImg)
//                 fs.unlink(oldpath, (err) => {
//                     //静默
//                 })
//             }
//             res.redirect('/')
//         } else {
//             res.send('<script>alert("编辑失败");location.href="/";</script>')
//         }
//     })
// }

// 实现编辑入库
ArticleController.update = (req, res) => {
    let { id, title, author, status, cat_id, content, oldImg } = req.body
    let update_time = getUnixTime();
    let imgPath;
    // let bind = [title,author,status,cat_id,content,update_time,id]
    if (req.file) {
        let { originalname, filename } = req.file
        let ext = originalname.substring(originalname.indexOf(`.`));
        let oldPath = path.join(__dirname, `../`, `uploads`, filename);
        let newPath = path.join(__dirname, `../`, `uploads`, filename) + ext;
        imgPath = `uploads/${filename}${ext}`
        fs.renameSync(oldPath, newPath)
    } else {
        imgPath = oldImg
    }
    let sql = `update article 
    set title = '${title}',img = '${imgPath}',author= '${author}',
    status= '${status}',cat_id= '${cat_id}',
    content = '${content}',update_time = '${update_time}' 
    where id = '${id}'`
    dbQueryPromise(sql).then(result => {
        if (result.affectedRows) {
            if (req.file) {
                let oldpath = path.join(__dirname, `../`, oldImg)
                fs.unlink(oldpath, () => {
                    //静默
                })
            }
            res.redirect(`/`)
        } else {
            res.send(`<script>alert("编辑失败");location.href="/";</script>`)
        }
    })
}

// 文章详情查看
// ArticleController.detail = (req, res) => {
//     let { id } = req.query;
//     let sql = `select t1.*,t2.cate_name from article t1 left join category t2 on t1.cat_id = t2.cate_id where t1.id=${id} `
//     dbQuery(sql, (err, rows) => {
//         // 渲染一个模板
//         console.log(rows)
//         res.render('detail.html', { article: rows[0] })
//     })

// }

// 文章详情查看
ArticleController.detail = (req, res) => {
    let { id } = req.query;
    let sql = `select t1.*,t2.cate_name from article t1 left join category t2 on t1.cat_id = t2.cate_id where t1.id=${id} `
    dbQueryPromise(sql).then(rows => {
        // 渲染一个模板  
        res.render(`detail.html`, { article: rows[0] })
    })
}

// 编辑文章
ArticleController.editContent = (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || `{}`);
    res.render(`editContent.html`, { userInfo })
}
ArticleController.updateArtilceContent = async (req, res) => {
    let { id, content } = req.body;
    let sql = `update article set content ="${content}" where id =${id}`
    let result = await dbQueryPromise(sql);
    console.log(result);
    res.json({
        code: 20000,
        message: `编辑文章成功`
    })
}
ArticleController.updateArtilceContent = async (req, res) => {
    let {
        id,
        content
    } = req.body;
    let sql = `update article set content = '${content}' where id = ${id}`
    let result = await dbQueryPromise(sql);
    console.log(result);
    res.json({
        code: 20000,
        message: `编辑文章成功`
    })

}

// 获取分页的时候,可以根据文章状态或文章标题搜索
ArticleController.articleCount = async (req, res) => {
    let { curr = 1, limit = 10, title, status } = req.query; // 1   10
    // 判断查询条件
    let where = ``;
    if (title) {
        where += `and title like "%${title}%"`
    }
    if (status) {
        where += `and status = ${status}`
    }
    // 查询文章总记录数
    let sql = `select count(*) as count from article  where 1 and is_delete = 0 ${where}`;
    // let result = await dbQueryPromise(sql)
    let offset = (curr - 1) * limit;
    // 查询分页数据
    let sql2 = `select t1.*,t2.cate_name from article  as t1 
                     left join category t2 on t1.cat_id = t2.cate_id 
                     where 1 and is_delete = 0 ${where}
                      order by t1.id desc limit
                     ${offset},${limit}`;
    // let result2 = await dbQueryPromise(sql2)
    // 并行优化
    let result = await Promise.all([dbQueryPromise(sql), dbQueryPromise(sql2)])
    res.json({
        count: result[0][0].count,
        data: result[1]
    })

}

module.exports = ArticleController;